package com.cookor.poi.modules.phy.mobile;

import com.cookor.poi.common.utils.ResultUtil;
import com.cookor.poi.modules.phy.entity.TWeixinUser;
import com.cookor.poi.modules.phy.service.TWeixinUserService;
import com.cookor.poi.modules.weixin.account.Account;
import com.cookor.poi.modules.weixin.entity.TWeixinConfig;
import com.cookor.poi.modules.weixin.service.TWeixinConfigService;
import com.xiaoleilu.hutool.json.JSONObject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping({"/api"})
@ResponseBody
public class ApiAuthController extends ApiBaseController {
  @Autowired
  private TWeixinConfigService weixinConfigService;
  
  @Autowired
  private TWeixinUserService tWeixinUserService;
  
  @RequestMapping({"/wx/auth"})
  public ResultUtil ResultUtil(HttpServletRequest request, HttpServletResponse response) {
    ResultUtil resultUtil = new ResultUtil(ResultUtil.SUCCESS_CODE);
    try {
      String code = request.getParameter("code");
      String tenantId = request.getParameter("siteId");
      TWeixinConfig wc = this.weixinConfigService.findByTenantId(Integer.valueOf(tenantId));
      String uniacid = wc.getId();
      if (StringUtils.isBlank(uniacid) || StringUtils.isBlank(code)) {
        resultUtil.setCode(ResultUtil.ERROR_CODE);
        resultUtil.setError("通信错误，请在微信中重新发起请求");
        this.logger.error("ApiAuthController auth error!", "通信错误，请在微信中重新发起请求");
        return resultUtil;
      } 
      Account account = Account.factory(uniacid);
      JSONObject jo = account.getOauthInfo(code);
      String openid = jo.getStr("openid");
      if (StringUtils.isNotBlank(openid)) {
        TWeixinUser user = this.tWeixinUserService.getByOpenId(openid);
        if (user == null) {
          jo = account.getUserInfo(openid);
          user = (TWeixinUser)jo.toBean(TWeixinUser.class);
          user.setUniacid(Integer.valueOf(Integer.parseInt(tenantId)));
          this.tWeixinUserService.save(user);
        } 
      } 
      resultUtil.putParams("openid", openid);
    } catch (Exception e) {
      resultUtil.setCode(ResultUtil.ERROR_CODE);
      resultUtil.setError(e.getMessage());
      this.logger.error("ApiAuthController auth error!", e);
    } 
    return resultUtil;
  }
}
